package com.cn.system.service.impl;

import com.cn.common.domain.Tree;
import com.cn.common.utils.BuildTree;
import com.cn.system.dao.DeptDao;
import com.cn.system.domain.DeptDO;
import com.cn.system.service.DeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.concurrent.LinkedBlockingQueue;


@Service
public class DeptServiceImpl implements DeptService {
    @Autowired
    private DeptDao deptDao;

    @Override
    public DeptDO get(String deptId) {
        return deptDao.get(deptId);
    }

    @Override
    public List<DeptDO> list(Map<String, Object> map) {
        return deptDao.list(map);
    }

    @Override
    public int count(Map<String, Object> map) {
        return deptDao.count(map);
    }

    @Override
    public int save(DeptDO sysDept) {
        return deptDao.save(sysDept);
    }

    @Override
    public int update(DeptDO sysDept) {
        return deptDao.update(sysDept);
    }

    @Override
    public int remove(String deptId) {
        return deptDao.remove(deptId);
    }

    @Override
    public int batchRemove(String[] deptIds) {
        return deptDao.batchRemove(deptIds);
    }

    @Override
    public Tree<DeptDO> getTree() {
        List<Tree<DeptDO>> trees = new ArrayList();
        List<DeptDO> sysDepts = deptDao.list(null);
        for (DeptDO sysDept : sysDepts) {
            Tree<DeptDO> tree = new Tree<>();
            tree.setId(sysDept.getDeptId());
            tree.setParentId(sysDept.getParentId());
            tree.setText(sysDept.getName());
            trees.add(tree);
        }
        // 默认顶级菜单为０，根据数据库实际情况调整
        Tree<DeptDO> t = BuildTree.build4Depth(trees, "0");
        return t;
    }

    @Override
    public boolean checkDeptHasUser(String deptId) {
        // TODO Auto-generated method stub
        //查询部门以及此部门的下级部门
        int result = deptDao.getDeptUserNumber(deptId);
        return result == 0 ? true : false;
    }

    @Override
    public List<String> listChildrenIds(String parentId) {
        List<DeptDO> deptDOS = list(null);
        return treeMenuList2(deptDOS, parentId);
    }

    private List<String> treeMenuList2(List<DeptDO> deptDOList, String pid) {
        List<String> childIds = new ArrayList<>();
        Queue<DeptDO> queue = new LinkedBlockingQueue();
        deptDOList.stream().filter(m -> pid.equalsIgnoreCase(m.getParentId())).forEach(m -> {
            queue.add(m);
            childIds.add(m.getDeptId());
        });
        while (!queue.isEmpty()) {
            DeptDO deptDO = queue.poll();
            deptDOList.stream().filter(m -> deptDO.getDeptId().equalsIgnoreCase(m.getParentId())).forEach(m -> {
                queue.add(m);
                childIds.add(m.getDeptId());
            });
        }
        return childIds;
    }

}
